<template>
  <div @touchmove.stop @touchmove.prevent class="container">
    <upload-success @closeSuc="closeSuc()" v-if="showSucFlag"></upload-success>
    <upload-failed @closeFail="closeFail()" v-if="showFailFlag"></upload-failed>
    <!-- <shop-picker v-if="showShopPicker" @close="showShopPicker = false" @change="shopNameChange"></shop-picker> -->
    <div id="targetContainer"></div>
    <div class="content animated fadeIn">
      <div class="form-item box box-ac">
        <div class="left">商户名</div>
        <!-- <div @click="showShopPicker = true" v-text="shopName" readonly class="right box-f1"></div> -->
        <input @blur="showShopPick = false" @focus="showShopPick = true" v-model="shopName" class="right box-f1">
        <shop-pick :keyword="shopName" :callback="shopCheck" v-if="showShopPick"></shop-pick>
      </div>
      <div class="form-item box box-ac">
        <div class="left">消费金额</div>
        <input v-model="money" class="right box-f1" type="tel">
      </div>
      <div class="form-item box box-ac">
        <div class="left">消费时间</div>
        <div id="datePicker" v-html="date" class="right box-f1"></div>
      </div>
      <div class="form-item box box-ac">
        <div class="left">手机号</div>
        <input v-model="userInfo.phone" class="right box-f1" type="tel">
      </div>
      <div :style="{'background-image':'url('+ticketImg+')'}" class="upload icon">
        <div @click="checkImg()" class="icon icon-upload"></div>
        <input @change="getFile($event)" ref="fileChecker" type="file" accept="image/*">
      </div>
      <div @click="submit()" class="icon icon-button icon-button-sure"></div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { openToast } from '@/assets/js/tools'
import uploadSuccess from '@/components/uploadSuccess'
import uploadFailed from '@/components/uploadFailed'
// import shopPicker from '@/components/shopPicker'
import shopPick from '@/components/shopPick'
// import ImgCompress from '../assets/js/imgCompress'
import lrz from 'lrz'
// import '@/assets/css/dataPicker.scss'
// import Picker from '@/assets/js/datePicker'
import '@/assets/css/DateSelector.scss'
import '@/assets/js/DateSelector'

export default {
  name: 'submit',
  components: {
    uploadSuccess,
    uploadFailed,
    shopPick
    // shopPicker
  },
  data () {
    return {
      ticketFile: null,
      ticketImg: null,
      shopName: '',
      money: '',
      date: '',
      showSucFlag: false,
      showFailFlag: false,
      picker: null,
      showShopPicker: false,
      showShopPick: false
    }
  },
  computed: mapState({
    activityGuid: 'activityGuid',
    userInfo: 'userInfo'
  }),
  mounted () {
    this.initPicker()
  },
  methods: {
    shopCheck (item) {
      this.shopName = item
    },
    checkImg () {
      this.$refs.fileChecker.click()
    },
    closeSuc () {
      this.showSucFlag = false
    },
    closeFail () {
      this.showFailFlag = false
    },
    shopNameChange (values) {
      this.shopName = values[0]
      this.showShopPicker = false
    },
    initPicker () {
      let _this = this
      let liHeight = Math.floor(document.documentElement.clientWidth / 7.5) * 0.8
      let date = new Date()
      let endTime = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()]
      this.picker = new DateSelector({
        input: 'datePicker',
        container: 'targetContainer',
        liHeight,
        type: 0,
        // 0：不需要tab切换，自定义滑动内容，建议小于三个；
        // 1：需要tab切换，【年月日】【时分】完全展示，固定死，可设置开始年份和结束年份
        param: [1, 1, 1, 1, 1],
        // 设置['year','month','day','hour','minute'],1为需要，0为不需要,需要连续的1
        beginTime: [2018, 1, 1, 0, 0],
        // 如空数组默认设置成1970年1月1日0时0分开始，如需要设置开始时间点，数组的值对应param参数的对应值。
        endTime: endTime,
        // 如空数组默认设置成次年12月31日23时59分结束，如需要设置结束时间点，数组的值对应param参数的对应值。
        recentTime: endTime,
        // 如不需要设置当前时间，被为空数组，如需要设置的开始的时间点，数组的值对应param参数的对应值。
        success: (arr, arr2) => {
          console.log(arr2)
          _this.date = arr2[0] + '-' + arr[1] + '-' + arr[2] + ' ' + arr[3] + ':' + arr[4]
          setTimeout(() => { _this.picker = null }, 10)
        }
      })
    },
    // showPicker () {
    //   this.$refs.picker.open()
    //   let _this = this
    //   let minYear = 2018
    //   let maxYear = 2019
    //   let picker = new Picker({
    //     type: '4', // 0-年, 1-年月, 2-月日, 3-年月日
    //     title: '请选择', // 标题（可选）
    //     maxYear: maxYear, // 最大年份（可选）
    //     minYear: minYear, // 最小年份（可选）
    //     separator: '-', // 日期分割符(可选)
    //     // defaultValue: '2018-03-22', // 默认值（可选）
    //     callBack: function (val) {
    //       _this.date = val
    //     }
    //   })
    // },
    uploadImage (cb) {
      this.$http({
        method: 'post',
        // type: 'file',
        // url: `${this.$config.baseUrl}/api/img/uploads`,
        url: `${this.$config.baseUrl}/api/img/base64`,
        data: {
          dataUrl: this.ticketImg
        }
      }).then(res => {
        console.log(res)
        if (res.status === 1) {
          this.ticketImg = res.data.url
          cb()
        } else {
          openToast({
            msg: res.message,
            duration: 1500
          })
          this.showFailFlag = true
        }
      })
    },
    submit () {
      if (!this.shopName) {
        openToast({
          msg: '请填写商户名',
          duration: 1500
        })
        return false
      }
      if (!/^[0-9]{0,5}(\.[0-9]{0,2})?$/.test(this.money) || this.money.length === 0) {
        openToast({
          msg: '请填写正确的金额',
          duration: 1500
        })
        return false
      }
      if (!this.date) {
        openToast({
          msg: '请填写消费时间',
          duration: 1500
        })
        return false
      }
      if (!/^1[23456789]\d{9}$/.test(this.userInfo.phone)) {
        openToast({
          msg: '请填写正确的手机号码',
          duration: 1500
        })
        return false
      }
      if (!this.ticketImg) {
        openToast({
          msg: '请选择小票图片',
          duration: 1500
        })
        return false
      }
      this.uploadImage(() => {
        this.addBill()
      })
    },
    addBill () {
      const { userGuid, nickname, headimgurl } = this.userInfo
      this.$http({
        method: 'post',
        url: `${this.$config.baseUrl}/api/stampuser/stamp_adds`,
        data: {
          activity_guid: this.activityGuid,
          user_guid: userGuid,
          nickname,
          headimgurl,
          shop_name: this.shopName,
          shop_money: this.money,
          shop_user: this.nickname,
          shop_phone: this.userInfo.phone,
          shop_date: this.date,
          shop_image: this.ticketImg
        }
      }).then(res => {
        if (res.status === 1) {
          this.showSucFlag = true
        } else {
          this.showFailFlag = true
        }
      })
    },
    getFile ($event) {
      this.ticketFile = $event.target.files[0]
      let _this = this
      this.$store.commit('isLoading', true)
      lrz(this.ticketFile, { width: 640 })
        .then(rst => {
          console.log('rst>>>>', rst)
          _this.ticketImg = rst.base64
          _this.ticketFile = rst.file
          $event.target.value = null
        })
        .always(() => {
          this.$store.commit('isLoading', false)
        })
      // let commpress = new ImgCompress({
      //   file: this.ticketFile,
      //   limitWidth: 800,
      //   limitSize: 1024 * 1024,
      //   // quality: 1,
      //   callback: (base64, file) => {
      //     console.log(this.ticketFile, file)
      //     _this.ticketImg = base64
      //     _this.ticketFile = file
      //     $event.target.value = null
      //   }
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../assets/css/mixins.scss';

.container{
  position: fixed;
  width:100%;
  height:100%;
  z-index:5;
  background-color:#FFF;
  color:#000;
}

.content{
  padding:.84rem .6rem .95rem .6rem;
}

.form-item{
  font-size:.3rem;
  margin-bottom:.4rem;
  .left{
    width:1.3rem;
    margin-right:.3rem;
    text-align: right;
  }
  .right{
    display: block;
    border:none;
    outline: none;
    height:.8rem;
    margin:0;
    padding:0;
    line-height: .8rem;
    padding-left:.3rem;
    padding-right:.3rem;
    border-radius:.8rem;
    background-color: #e5e5e5;
    border:none;
  }
}
.upload{
  margin:.96rem auto;
  width:2.16rem;
  height:2.16rem;
}
.icon-upload{
  opacity: 0.3;
  width:100%;
  height:100%;
  z-index:2;
  @include bg-image('../assets/images/icon-upload')
}
input[type=file]{
  display:none
}
.icon-button-sure{
  margin-top:.86rem;
  @include bg-image('../assets/images/icon-button-sure');
}
</style>
